package memo.action;

import java.util.Date;
import java.util.List;
import memo.adapter.Memo_listviewadapter;
import memo.dao.ListMemoDAO;
import memo.pojo.ListMemo;
import model.pojo.Employee;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Shader;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import approve.action.LoginActivity;
import approve.action.LogoutActivity;
import approve.action.MainEApproval;
import approve.action.R;

public class Memo_listview extends Activity {
	TextView logout,username,home,welcome;
	TextView lbListPrivateMemo,nodata;
	Button bttAddNewMemo;
	ListView listMemo;
	Button buttonBack;

	ListView lstApprove;
	ListMemoDAO listMemoDAO = new ListMemoDAO();
	Memo_listviewadapter listviewadapter;

	String valueTitle="";
	String valueContent="";
	
	private final Handler uiHandler=new Handler();
	private boolean isUpdateRequired=false;
	TextView tvwaiting;
	LayoutInflater inflaterwaiting;
	View textEntryViewwaiting;
	AlertDialog.Builder builderwaiting;
	AlertDialog alertwaiting;
	int flagviewpopup=0,kt=0;
	
	public AlertDialog getAlertwaiting() {
		return alertwaiting;
	}

	public void setAlertwaiting(AlertDialog alertwaiting) {
		this.alertwaiting = alertwaiting;
	}

	public boolean isUpdateRequired() {
		return isUpdateRequired;
	}

	public void setUpdateRequired(boolean isUpdateRequired) {
		this.isUpdateRequired = isUpdateRequired;
	}

	public Handler getUiHandler() {
		return uiHandler;
	}
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try{
			initall();
		}catch(Exception e){
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}

	public void initall(){
		
		setContentView(R.layout.memo_listview);

		bttAddNewMemo = (Button)findViewById(R.id.buttonAddNewMemo);
		bttAddNewMemo.setText(LoginActivity.lang.getString("add11"));

		listMemo = (ListView)findViewById(R.id.listViewPrivateMemo);

		logout=(TextView)findViewById(R.id.logout);
		username=(TextView)findViewById(R.id.username);
		logout.setText(LoginActivity.lang.getString("Logout"));

		logout.setOnClickListener(listenerLogout);
		username.setText(LoginActivity.emp.getUserName());

		welcome = (TextView)findViewById(R.id.welcome);
		welcome.setText(LoginActivity.lang.getString("ac_Welcome"));

		lbListPrivateMemo = (TextView)findViewById(R.id.lbListPrivateMemo);
		lbListPrivateMemo.setText(LoginActivity.lang.getString("listprivatememo"));
		nodata =(TextView)findViewById(R.id.nodata);
		
		buttonBack = (Button)findViewById(R.id.buttonBack);
		buttonBack.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				buttonBack.setBackgroundResource(R.drawable.bg_back_pressed);
				Intent intent = new Intent(Memo_listview.this,MainEApproval.class);
				startActivity(intent);
				finish();
			}
		});

		RelativeLayout relativeLayout = (RelativeLayout)findViewById(R.id.relativeTitle);

		Resources res = getResources();
		final BitmapDrawable background = (BitmapDrawable) res.getDrawable(R.drawable.bg_menu_item);
		background.setTileModeX(Shader.TileMode.REPEAT);
		background.setTileModeY(Shader.TileMode.REPEAT);
		background.setDither(true);
		relativeLayout.setBackgroundDrawable(background);

		loadContentPrivateMemo();
		
		inflaterwaiting = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		textEntryViewwaiting = inflaterwaiting.inflate(R.layout.waiting, null);
		tvwaiting=(TextView)textEntryViewwaiting.findViewById(R.id.TextView01);					
		tvwaiting.setText(LoginActivity.lang.getString("waiting")+"...");

		builderwaiting = new AlertDialog.Builder(Memo_listview.this);
		builderwaiting.setView(textEntryViewwaiting);
		builderwaiting.setCancelable(false);
		alertwaiting = builderwaiting.create();
	}
	
	public void loadContentPrivateMemo(){
		listviewadapter = new Memo_listviewadapter(Memo_listview.this, loadListPrivateMemo(), LoginActivity.lang.getString("created-date"));
		listMemo.setAdapter(listviewadapter);

		listMemo.setOnItemClickListener(processItemListMemo);

		bttAddNewMemo.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				bttAddNewMemo.setBackgroundResource(R.drawable.bt_general_pressed);
				if(flagviewpopup==0){
					flagviewpopup=1;
					processBttAddNewMemo();	
				}
							
			}
		});
	}

	private List<ListMemo> loadListPrivateMemo(){
		List<ListMemo> lst = listMemoDAO.getAllMemoEmp(LoginActivity.emp.getIdemployee(), LoginActivity.database);
		if(lst.size()==0){
			nodata.setVisibility(View.VISIBLE);
			listMemo.setVisibility(View.GONE);
			nodata.setText(LoginActivity.lang.getString("nodata"));
		}else{
			nodata.setVisibility(View.GONE);
			listMemo.setVisibility(View.VISIBLE);
		}
		return lst;
	}

	

	private OnClickListener listenerLogout=new OnClickListener() {

		public void onClick(View v) {
			logout.setTextColor(Color.parseColor("#1188ff"));
			LoginActivity.flagruntimer=true;
			LoginActivity.soluong=0;
			LoginActivity.emp=new Employee();
			MainEApproval.mNotificationManager.cancel(MainEApproval.SIMPLE_NOTFICATION_ID);
			MainEApproval.timer.cancel();			
			Intent i=new Intent(Memo_listview.this, LogoutActivity.class);
			startActivity(i);
			finish();
		}
	};

	public String[] listAllApprove(String value) {
		String[] menu = null;
		if (value.equals("EN")) {
			menu = getResources().getStringArray(R.array.approval_en);
		} else if (value.equals("KR")) {
			menu = getResources().getStringArray(R.array.approval_kr);
		} else {
			menu = getResources().getStringArray(R.array.approval_vn);
		}
		return menu;
	}

	protected void processBttAddNewMemo () {
		Rect displayRectangle = new Rect();
		Window window = Memo_listview.this.getWindow();
		window.getDecorView().getWindowVisibleDisplayFrame(displayRectangle);


		LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);          
		final View textEntryView = inflater.inflate(R.layout.memo_addnew, null);

		final TextView lbtitleMemo = (TextView)textEntryView.findViewById(R.id.memo_add_tvtitle);
		final TextView lbcontentMemo = (TextView)textEntryView.findViewById(R.id.memo_add_tvcontent);

		lbtitleMemo.setText(LoginActivity.lang.getString("title"));
		lbcontentMemo.setText(LoginActivity.lang.getString("content"));


		final EditText edTitleMemo = (EditText)textEntryView.findViewById(R.id.memo_add_ettitle);
		edTitleMemo.setText(valueTitle);

		final EditText edContentMemo = (EditText)textEntryView.findViewById(R.id.memo_add_etcontent);
		edContentMemo.setText(valueContent);

		textEntryView.setMinimumWidth((int)(displayRectangle.width() * 1f));
		textEntryView.setMinimumHeight((int)(displayRectangle.height() * 1f));

		
		final Button buttonSave = (Button)textEntryView.findViewById(R.id.bttSaveMemo);
		buttonSave.setText(LoginActivity.lang.getString("save"));
		final Button buttonReset = (Button)textEntryView.findViewById(R.id.bttResetMemo);
		buttonReset.setText(LoginActivity.lang.getString("ac_ma_Reset"));
		final Button buttonClose = (Button)textEntryView.findViewById(R.id.bttCloseMemo);
		buttonClose.setText(LoginActivity.lang.getString("Close"));

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(LoginActivity.lang.getString("addnewprivatememo"));
		builder.setView(textEntryView);
		builder.setCancelable(false);
		final AlertDialog alert = builder.create();
		alert.show();
		
		buttonReset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				edTitleMemo.setText("");
				edContentMemo.setText("");
			}
		});

		buttonClose.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				bttAddNewMemo.setBackgroundResource(R.drawable.bt_general_normal);
				flagviewpopup=0;
				alert.cancel();
			}
		});

		buttonSave.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				bttAddNewMemo.setBackgroundResource(R.drawable.bt_general_normal);
				
				if(!edTitleMemo.getText().toString().equals("")){
					alert.cancel();
					alertwaiting.show();
					try{
						new Thread(){
							public void run() {
								valueTitle="";
								valueContent="";

								listMemoDAO.createMemo(new ListMemo(edTitleMemo.getText().toString(),edContentMemo.getText().toString(),LoginActivity.emp,new Date(),1), LoginActivity.database);							
								
								uiHandler.post( new Runnable(){
									@Override
									public void run() {
										if(isUpdateRequired){
										}else{
											loadContentPrivateMemo();
											alertwaiting.cancel();
										}
									}
								} );
							}
						}.start();
					}catch (Exception e) {}
					
					flagviewpopup=0;
				}else{
					valueTitle = edTitleMemo.getText().toString();
					valueContent = edContentMemo.getText().toString();
					Toast.makeText(getApplicationContext(), LoginActivity.lang.getString("isempty"),Toast.LENGTH_LONG).show();
				}
				
				
			}
		});
	}

	protected OnItemClickListener processItemListMemo = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,
				long arg3) {

			ListMemo itemMemo = (ListMemo)listMemo.getItemAtPosition(position);
			Intent intent = new Intent(Memo_listview.this, Memo_oneview.class);
			intent.putExtra("itemmemo", itemMemo);
			startActivity(intent);
			finish();
		}
	};


	public void onBackPressed() {
		
		Memo_listview.this.getAlertwaiting().show();
		try{
			new Thread(){
				public void run() {
					Intent intent = new Intent(Memo_listview.this,MainEApproval.class);
					startActivity(intent);
					finish();
					Memo_listview.this.getUiHandler().post( new Runnable(){
						@Override
						public void run() {
							if(Memo_listview.this.isUpdateRequired()){
							}else{
								Memo_listview.this.getAlertwaiting().cancel();
							}
						}
					} );
				}
			}.start();
		}catch (Exception e) {}
	};

	// Main menu
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = new MenuInflater(getApplicationContext());
		if(LoginActivity.typeLang.equals("EN")){
			inflater.inflate(R.menu.option_main_menu, menu);
		}else if(LoginActivity.typeLang.equals("VN")){
			inflater.inflate(R.menu.option_main_menuvn, menu);
		}else{
			inflater.inflate(R.menu.option_main_menukr, menu);
		}

		setMenuBackground();
		return true;
	}
	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  
			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  

					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.drawable.border_footer);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  

			}  
		});  
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(LoginActivity.typeLang.equals("VN")){
			switch (item.getItemId()) {
			case R.id.menu_eappvn:
				processMenuEApproval();
				return true;
			case R.id.menu_primemovn:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else if(LoginActivity.typeLang.equals("KR")){
			switch (item.getItemId()) {
			case R.id.menu_eappkr:
				processMenuEApproval();
				return true;
			case R.id.menu_primemokr:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else{
			switch (item.getItemId()) {
			case R.id.menu_eapp:
				processMenuEApproval();
				return true;
			case R.id.menu_primemo:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	}

	// process on click menu e-approval
	public void processMenuEApproval(){
		Intent intent = new Intent(Memo_listview.this,MainEApproval.class);
		startActivity(intent);
		finish();
	}

	public void processMenuPrivateMemo(){
		loadContentPrivateMemo();
	}
}